﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using FixedPropertyManagement.Models;

namespace FixedPropertyManagement
{
    public partial class _default : System.Web.UI.Page
    {       
        PropertyMangementEntities3 db = new PropertyMangementEntities3();
        public static string userTypeMa;//判断用户类型
        public static string userMa;//判断用户权限

        #region load及相关事件
        protected void Page_Load(object sender, EventArgs e)
        {
            ScriptResourceDefinition srd1 = new ScriptResourceDefinition();
            srd1.Path = "~/scripts/jquery_3.6_min.js";
            ScriptManager.ScriptResourceMapping.AddDefinition("jquery", srd1);
           
            if (!this.IsPostBack)
            {
                //获取相关登录数据
                getNum_Name();             
            }
        }
        //获取账号和姓名
        private void getNum_Name()
        {
            if(Session["userNum"] != null)
            {
                lblNum.Text = Session["userNum"].ToString();
                lblName.Text = Session["userName"].ToString();
                userTypeMa = Session["userType"].ToString();
                userMa = Session["userMange"].ToString();
                //资源
                ShowProperty();
                getPropertyData();
                getPropertyData1();
                //部门
                getDepartMa();
                //员工
                getEmployeeData();
                getEmData();
                //个人信息
                personSet();
            }
            else
            {
                Response.Write("<script>window.location = 'aspxs/login.aspx'</script>");
            }
        }
        //ddl 资源数据源
        private void getPropertyData()
        {
            var result = db.PropertyTypes;
            ListItem li = new ListItem("-请选择-", "0");
            ddlType1.Items.Add(li);
            if (result != null)
            {            
                ddlType1.DataSource = result.ToList();
                ddlType1.DataBind();
            }
                
        }
        //ddl 资源数据源
        private void getPropertyData1()
        {
            var result = db.PropertyTypes;
            if (result != null)
            {
                ddlPerType.DataSource = result.ToList();
                ddlPerType.DataBind();
            }
        }
        //ddl 用户部门数据源
        private void getEmData()
        {
            var result = db.Departments.Where(d=>d.DepartId != 520 );
            ListItem li = new ListItem("-请选择-", "0");
            ddlType3.Items.Add(li);
            if (result != null)
            {
                ddlType3.DataSource = result.ToList();
                ddlType3.DataBind();
                ddlEmplyeeType.DataSource = result.ToList();
                ddlEmplyeeType.DataBind();
            }
        }
        #endregion

        #region 个人信息
        private void personSet()
        {
            string id = lblNum.Text;
            var result = db.Employees.Where(em => em.EmpId.ToString() == id).FirstOrDefault();
            if(result != null)
            {
                userNum.Text = id;
                userName.Text = result.Name.Trim();
                lblName.Text = result.Name.Trim();
                var de = db.Departments.Where(d => d.DepartId == result.DepartId).FirstOrDefault();
                lblUserType.Text = de.Name.Trim();
                userTell.Text = result.Tell.Trim();
                if (result.IsManger == true)
                {
                    userManger.Text = "是";
                }
                else userManger.Text = "否";
            }       
        }       
        //修改
        private void personChange()
        {
            string id = userNum.Text.Trim();        
            string name = userName.Text.Trim();
            string tell = userTell.Text.Trim();
            var result = db.Employees.Where(em => em.EmpId.ToString() == id).FirstOrDefault();
            if (name != "")
            {
                result.Name = name;
                lblName.Text = name;
            }
            if (tell != "") result.Tell = tell;                
            try
            {
                db.SaveChanges();
                ShowProperty();
                getDepartMa();
                getEmployeeData();
                Response.Write("<script>alert('保存成功！')</script>");
            }
            catch(Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
        protected void btnSave_Click(object sender, EventArgs e)
        {
            personChange();
        }
        #endregion

        #region gridView资源相关操作
        //删除和修改定位是全部显示还是部门显示，还是单个资源显示
        private void propertyShow()
        {
            string ddlname = ddlType1.SelectedItem.Text;
            string search = txtSearch1.Text.Trim();
            if (ddlname.Equals("-请选择-") && search.Equals("请输入资源编号或名称"))
            {
                ShowProperty();
            }
            else if (!ddlname.Equals("-请选择-") && search.Equals("请输入资源编号或名称"))
            {
                ddlProperty();
            }
            else
            {
                propertySearch();
            }
        }
        //搜索
        private void propertySearch()
        {
            string search = txtSearch1.Text.Trim();
            var employ1 = db.Employees.Where(em => em.Name == search).FirstOrDefault();
            if (employ1 != null) search = employ1.EmpId.ToString();
            ddlType1.SelectedValue = "0";
            if (userTypeMa == "管理部")
            {
                var result = from b in db.Properties
                             join em in db.Employees
                             on b.EmpId equals em.EmpId into bem
                             from be in bem.DefaultIfEmpty()
                             join c in db.PropertyTypes
                             on b.ProTypeId equals c.ProTypeId
                             where b.ProId.ToString() == search || b.Name.Contains(search) || b.EmpId.ToString() == search || b.StoreLocation.Contains(search) || b.PurchaseDate.ToString().Substring(0,4) == search
                             select new
                             {
                                 编号 = b.ProId,
                                 名称 = b.Name,
                                 规格 = b.Specification,
                                 照片 = b.Image,
                                 价格 = b.Price,
                                 购入日期 = b.PurchaseDate,
                                 存放位置 = b.StoreLocation,
                                 类别 = c.Name,
                                 保管人 = be.Name == null ? "" : be.Name
                             };
                if (result.Count() == 0)
                {
                    Response.Write("<script>alert('" + search + "在系统中没有相关数据！')</script>");

                }
                try
                {
                    gvProperty.DataSource = result.ToList();
                    gvProperty.DataBind();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
                            
            }
            else
            {
                string emId = lblNum.Text.Trim();
                var employ = db.Employees.Where(em => em.EmpId.ToString() == emId).FirstOrDefault();
                var dep = db.Departments.Where(d => d.DepartId == employ.DepartId).FirstOrDefault();
                if(dep.EmpId == null)
                {
                    dep.EmpId = -1;
                }
                var result1 = from b in db.Properties
                              join em in db.Employees
                              on b.EmpId equals em.EmpId into bem
                              from be in bem.DefaultIfEmpty()
                              join c in db.PropertyTypes
                              on b.ProTypeId equals c.ProTypeId
                              where (b.ProId.ToString() == search || b.Name.Contains(search) || b.StoreLocation.Contains(search) || b.PurchaseDate.ToString().Substring(0, 4) == search || b.EmpId.ToString() == search) && b.EmpId == dep.EmpId
                              select new
                              {
                                  编号 = b.ProId,
                                  名称 = b.Name,
                                  规格 = b.Specification,
                                  照片 = b.Image,
                                  价格 = b.Price,
                                  购入日期 = b.PurchaseDate,
                                  存放位置 = b.StoreLocation,
                                  类别 = c.Name,
                                  保管人 = be.Name == null ? "" : be.Name
                              };
                if (result1.Count() == 0)
                {
                    Response.Write("<script>alert('" + search + "在系统中没有相关数据！')</script>");
                }
                try
                {
                    gvProperty.DataSource = result1.ToList();
                    gvProperty.DataBind();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
        }
        protected void btnSearch1_Click(object sender, EventArgs e)
        {
            propertySearch();
        }
        //下拉框
        private void ddlProperty()
        {
            int pId = Int32.Parse(ddlType1.SelectedValue);
            txtSearch1.Text = "请输入资源编号或名称";
            if (pId == 0)
            {
                ShowProperty();
            }
            else
            {
                if (userTypeMa == "管理部")
                {
                    string name = ddlType1.SelectedItem.Text.Trim();
                    var result = from b in db.Properties
                                 join c in db.PropertyTypes
                                 on b.ProTypeId equals c.ProTypeId
                                 join d in db.Employees
                                 on b.EmpId equals d.EmpId into bdm
                                 from bd in bdm.DefaultIfEmpty()
                                 where b.ProTypeId == pId
                                 select new
                                 {
                                     编号 = b.ProId,
                                     名称 = b.Name,
                                     规格 = b.Specification,
                                     照片 = b.Image,
                                     价格 = b.Price,
                                     购入日期 = b.PurchaseDate,
                                     存放位置 = b.StoreLocation,
                                     类别 = c.Name,
                                     保管人 = bd.Name == null ? "" : bd.Name
                                 };
                    if (result.Count() == 0)
                    {
                        Response.Write("<script>alert('" + name + "在系统中没有相关数据！')</script>");
                    }
                    
                    try
                    {
                        gvProperty.DataSource = result.ToList();
                        gvProperty.DataBind();
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                    }
                    
                }
                else
                {
                    string emId = lblNum.Text.Trim();
                    var employ = db.Employees.Where(em => em.EmpId.ToString() == emId).FirstOrDefault();
                    var dep = db.Departments.Where(d => d.DepartId == employ.DepartId).FirstOrDefault();
                    if (dep.EmpId == null)
                    {
                        dep.EmpId = -1;
                    }
                    string name = ddlType1.SelectedItem.Text.Trim();
                    var result1 = from b in db.Properties
                                  join c in db.PropertyTypes
                                  on b.ProTypeId equals c.ProTypeId
                                  join d in db.Employees
                                  on b.EmpId equals d.EmpId into bdm
                                  from bd in bdm.DefaultIfEmpty()
                                  where b.ProTypeId == pId && b.EmpId == dep.EmpId
                                  select new
                                  {
                                      编号 = b.ProId,
                                      名称 = b.Name,
                                      规格 = b.Specification,
                                      照片 = b.Image,
                                      价格 = b.Price,
                                      购入日期 = b.PurchaseDate,
                                      存放位置 = b.StoreLocation,
                                      类别 = c.Name,
                                      保管人 = bd.Name == "" ? "" : bd.Name
                                  };
                    if (result1.Count() == 0)
                    {
                        Response.Write("<script>alert('" + name + "在系统中没有相关数据！')</script>");
                    }
                    try
                    {
                        gvProperty.DataSource = result1.ToList();
                        gvProperty.DataBind();
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                    }
                }
            }
        }
        protected void ddlType1_SelectedIndexChanged(object sender, EventArgs e)
        {
            ddlProperty();
        }
        //gv数据源
        protected void ShowProperty() 
        {
            if(userTypeMa.Equals("管理部"))
            {
                var result = from b in db.Properties
                             join em in db.Employees
                             on b.EmpId equals em.EmpId into bem
                             from be in bem.DefaultIfEmpty()
                             join c in db.PropertyTypes
                             on b.ProTypeId equals c.ProTypeId
                             select new
                             {
                                 编号 = b.ProId,
                                 名称 = b.Name,
                                 规格 = b.Specification,
                                 照片 = b.Image,
                                 价格 = b.Price,
                                 购入日期 = b.PurchaseDate,
                                 存放位置 = b.StoreLocation,
                                 类别 = c.Name,
                                 保管人 = be == null ? "" : be.Name
                             };
                if(result != null)
                {
                    try
                    {
                        gvProperty.DataSource = result.ToList();
                        gvProperty.DataBind();
                    }catch(Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                    }                 
                }
            }else
            {
                string emId = lblNum.Text.Trim();
                var employ = db.Employees.Where(em => em.EmpId.ToString() == emId).FirstOrDefault();
                var dep = db.Departments.Where(d => d.DepartId == employ.DepartId).FirstOrDefault();
                if (dep.EmpId == null)
                {
                    dep.EmpId = -1;
                }
                var result1 = from b in db.Properties
                                join c in db.PropertyTypes
                                on b.ProTypeId equals c.ProTypeId
                                join em in db.Employees
                                on b.EmpId equals em.EmpId into bem
                                from be in bem.DefaultIfEmpty()
                                where b.EmpId == dep.EmpId
                                select new
                                {
                                    编号 = b.ProId,
                                    名称 = b.Name,
                                    规格 = b.Specification,
                                    照片 = b.Image,
                                    价格 = b.Price,
                                    购入日期 = b.PurchaseDate,
                                    存放位置 = b.StoreLocation,
                                    类别 = c.Name,
                                    保管人 = be == null ? "" : be.Name
                                };
                if (result1 != null)
                {
                    try
                    {
                        gvProperty.DataSource = result1.ToList();
                        gvProperty.DataBind();
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                    }
                }
            }
            
        }
        //gv换页操作
        protected void gvProperty_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            gvProperty.PageIndex = e.NewPageIndex;
            propertyShow();
        }
        //编辑
        protected void gvProperty_RowEditing(object sender, GridViewEditEventArgs e)
        {
            gvProperty.EditIndex = e.NewEditIndex; //切换到编辑状态          
            propertyShow();
        }
        //接触和点击删除引发的事件
        protected void gvProperty_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                e.Row.Attributes.Add("onmouseover", "bg=this.style.backgroundColor;c=this.style.color;this.style.backgroundColor='#c4d5ff';this.style.color='#fff';");
                e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=bg;this.style.color=c");
                e.Row.Cells[0].Attributes.Add("style", "border: 1px solid #333");
                e.Row.Cells[1].Attributes.Add("style", "border: 1px solid #333");
                e.Row.Cells[2].Attributes.Add("style", "border: 1px solid #333");
                e.Row.Cells[3].Attributes.Add("style", "border: 1px solid #333");
                e.Row.Cells[4].Attributes.Add("style", "border: 1px solid #333");
                e.Row.Cells[5].Attributes.Add("style", "border: 1px solid #333");
                e.Row.Cells[6].Attributes.Add("style", "border: 1px solid #333");
                e.Row.Cells[7].Attributes.Add("style", "border: 1px solid #333");
                e.Row.Cells[8].Attributes.Add("style", "border: 1px solid #333");
                e.Row.Cells[9].Attributes.Add("style", "border: 1px solid #333");
                e.Row.Cells[10].Attributes.Add("style", "border: 1px solid #333");
                try
                {
                    //获取“删除”链接
                    LinkButton lnkbtnDelete = (LinkButton)e.Row.Cells[10].Controls[0];
                    //添加JavaScript代码实现客户端信息的提示
                    lnkbtnDelete.OnClientClick = "return confirm('您真要删除资产名称为" +
                e.Row.Cells[1].Text.Trim() + "的记录吗?');";
                }
                catch
                {
                    return;
                }
            }
        }
        //取消编辑
        protected void gvProperty_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            //取消编辑
            gvProperty.EditIndex = -1;
            propertyShow();
        }
        //更新操作
        protected void gvProperty_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            if(userMa == "是")
            {
                string id = gvProperty.Rows[e.RowIndex].Cells[0].Text.Trim().ToString();
                string name = ((TextBox)gvProperty.Rows[e.RowIndex].Cells[1].Controls[0]).Text.Trim().ToString();
                string info = ((TextBox)gvProperty.Rows[e.RowIndex].Cells[2].Controls[0]).Text.Trim().ToString();
                string imagename = ((TextBox)gvProperty.Rows[e.RowIndex].Cells[3].Controls[0]).Text.Trim().ToString();
                string image = imagename;
                string price = ((TextBox)gvProperty.Rows[e.RowIndex].Cells[4].Controls[0]).Text.Trim().ToString();
 /*               string time = ((TextBox)gvProperty.Rows[e.RowIndex].Cells[5].Controls[0]).Text.Trim().ToString();*/
                string locat = ((TextBox)gvProperty.Rows[e.RowIndex].Cells[6].Controls[0]).Text.Trim().ToString();
                string type = ((TextBox)gvProperty.Rows[e.RowIndex].Cells[7].Controls[0]).Text.Trim().ToString();
                string emName = ((TextBox)gvProperty.Rows[e.RowIndex].Cells[8].Controls[0]).Text.Trim().ToString();
                var result = db.Properties.Where(p => p.ProId.ToString() == id).FirstOrDefault();
                if (name != "") result.Name = name;
                var em1 = db.Employees.Where(em => em.EmpId == result.EmpId).FirstOrDefault();
                if( em1 != null)
                {                 
                    if(em1.Name == emName)
                    {
                        name = "";
                    }
                }

                if (info != "") result.Specification = info;
                if (imagename != "")
                {
                    string fixname = image.Substring(image.LastIndexOf(".") + 1).ToLower();
                    if (fixname == "png" || fixname == "jpg" || fixname == "gif")
                    {
                        result.Image = image;                    
                    }
                    else
                    {
                        Response.Write("<script>alert('图片格式不正确，无法修改！')</script>");
                        return;
                    }                  
                }
                if (price != "") result.Price = Int32.Parse(price);
                if (locat != "") result.StoreLocation = locat;
                try
                {   
                    if (emName == "")
                    {
                        if (userTypeMa == "管理部")  result.EmpId = null;
                        db.SaveChanges();
                        gvProperty.EditIndex = -1;
                        propertyShow();
                    }
                    else
                    {
                        if (userTypeMa == "管理部")
                        {                          
                            var employ = db.Employees.Where(em => em.Name == emName && em.IsManger == true).FirstOrDefault();
                            if (employ != null)
                            {
                                result.EmpId = employ.EmpId;
                            }
                            else
                            {
                                Response.Write("<script>alert('系统中部门管理人并没有名字为" + emName + "的员工')</script>");
                                return;
                            }
                        }                   
                        db.SaveChanges();
                        gvProperty.EditIndex = -1;
                        propertyShow();
                    }
                }
                catch (Exception ex)
                {
                    Response.Write("<script>alert('修改中出现错误，" + ex.Message + "')</script>");
                }
            }
            else
            {
                gvProperty.EditIndex = -1;
                propertyShow();
                Response.Write("<script>alert('管理权限不够，无法操作！')</script>");
            }
 

        }
        //删除事件
        protected void gvProperty_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            if (userTypeMa == "管理部")
            {
                string id = gvProperty.Rows[e.RowIndex].Cells[0].Text.Trim().ToString();
                var result = db.Properties.Where(r => r.ProId.ToString() == id).FirstOrDefault();
                db.Properties.Remove(result);
                
                db.SaveChanges();
                propertyShow();
            }
            else
            {
                Response.Write("<script>alert('管理权限不够，无法操作！')</script>");
            }

        }
        #endregion

        #region gridView部门相关操作
        //获取全部部门
        private void getDepartMa()
        {
            var result = from d in db.Departments
                            join em in db.Employees
                            on d.EmpId equals em.EmpId into dem
                            from de in dem.DefaultIfEmpty()
                            where d.DepartId != 520
                            select new
                            {
                                编号 = d.DepartId,
                                名称 = d.Name,
                                人数 = d.Count,
                                管理人 = de == null ? "" : de.Name,
                                简介 = d.Info
                            };
            if(result == null)
            {
                Response.Write("<script>alert('系统中没有部门相关数据！')</script>");
            }
            try
            {
                gvDepartment.DataSource = result.ToList();
                gvDepartment.DataBind();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
        //编辑
        protected void gvDepartment_RowEditing(object sender, GridViewEditEventArgs e)
        {
            gvDepartment.EditIndex = e.NewEditIndex; //切换到编辑状态          
            getDepartMa();
        }
        //部门删除
        protected void gvDepartment_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            if (userTypeMa == "管理部")
            {
                string id = gvDepartment.Rows[e.RowIndex].Cells[0].Text.Trim().ToString();
                var result = db.Departments.Where(d => d.DepartId.ToString() == id).FirstOrDefault();
                db.Departments.Remove(result);
                var re = db.Employees.Where(em => em.DepartId.ToString() == id);
                if(re != null)
                {
                    foreach(var ee in re)
                    {
                        db.Employees.Remove(ee);
                    }
                }
                db.SaveChanges();
                getDepartMa();
            }
            else
            {
                Response.Write("<script>alert('管理权限不够，无法操作！')</script>");
            }
            
        }
        //更新
        protected void gvDepartment_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            if(userTypeMa == "管理部")
            {
                int id = Int32.Parse(gvDepartment.Rows[e.RowIndex].Cells[0].Text.Trim().ToString());
                string name = ((TextBox)(gvDepartment.Rows[e.RowIndex].Cells[1].Controls[0])).Text.Trim().ToString();
                string emName = ((TextBox)(gvDepartment.Rows[e.RowIndex].Cells[3].Controls[0])).Text.Trim().ToString();
                string info = ((TextBox)(gvDepartment.Rows[e.RowIndex].Cells[4].Controls[0])).Text.Trim().ToString();
                var count = db.Employees.Where(em => em.DepartId == id);
                var result = db.Departments.Where(d => d.DepartId == id).FirstOrDefault();
                result.Count = count.Count();
                if (name != "")
                {
                    result.Name = name;
                }
                if (info != "") result.Info = info;
                if (emName != "")
                {
                    var employ = db.Employees.Where(em => em.Name == emName && em.DepartId == result.DepartId).FirstOrDefault();
                    if (employ != null)
                    {
                        var old = db.Employees.Where(em => em.EmpId == result.EmpId).FirstOrDefault();
                        if (old != null)
                        {
                            old.IsManger = false;
                            var per = db.Properties.Where(p => p.EmpId == old.EmpId);
                            if (per.Count() != 0)
                            {
                                foreach (var p in per)
                                {
                                    p.EmpId = employ.EmpId;
                                }
                                ShowProperty();
                            }
                        }
                        employ.IsManger = true;
                        result.EmpId = employ.EmpId;
                        try
                        { 
                            gvDepartment.EditIndex = -1;
                            getEmployeeData();
                            db.SaveChanges();
                            getDepartMa();
                           
                        }
                        catch (Exception ex)
                        {
                            Response.Write("<script>alert('修改中出现错误，" + ex.Message + "')</script>");
                        }
                    }
                    else
                    {
                        Response.Write("<script>alert('" + result.Name.Trim() + "没有该员工')</script>");
                        return;
                    }

                }
                else
                {
                    var old1 = db.Employees.Where(em => em.DepartId == id && em.IsManger == true).FirstOrDefault();
                    if (old1 != null) {
                        old1.IsManger = false;
                        var pe = db.Properties.Where(p => p.EmpId == old1.EmpId);
                        if (pe.Count() != 0)
                        {
                            foreach (var p in pe)
                            {
                                p.EmpId = null;
                            }
                            ShowProperty();
                        }
                    }
                    result.EmpId = null;
                    
                    db.SaveChanges();
                    gvDepartment.EditIndex = -1;
                    getEmployeeData();
                    getDepartMa();
                }
            }else
            {
                gvDepartment.EditIndex = -1;
                getDepartMa();
                Response.Write("<script>alert('管理权限不够，无法操作！')</script>");
            }
                             
        }
        //修饰
        protected void gvDepartment_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                e.Row.Attributes.Add("onmouseover", "bg=this.style.backgroundColor;c=this.style.color;this.style.backgroundColor='#c4d5ff';this.style.color='#fff';");
                e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=bg;this.style.color=c");
                e.Row.Cells[0].Attributes.Add("style", "border: 1px solid #333");
                e.Row.Cells[1].Attributes.Add("style", "border: 1px solid #333");
                e.Row.Cells[2].Attributes.Add("style", "border: 1px solid #333");
                e.Row.Cells[3].Attributes.Add("style", "border: 1px solid #333");
                e.Row.Cells[4].Attributes.Add("style", "border: 1px solid #333");
                e.Row.Cells[5].Attributes.Add("style", "border: 1px solid #333");
                e.Row.Cells[6].Attributes.Add("style", "border: 1px solid #333");
                try
                {
                    //获取“删除”链接
                    LinkButton lnkbtnDelete = (LinkButton)e.Row.Cells[6].Controls[0];
                    //添加JavaScript代码实现客户端信息的提示
                    lnkbtnDelete.OnClientClick = "return confirm('您真要删除部门名称为" +
                    e.Row.Cells[1].Text.Trim() + "的记录吗?');";
                }
                catch
                {
                    return;
                }
            }
        }
        //换页
        protected void gvDepartment_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            gvDepartment.PageIndex = e.NewPageIndex;
            getDepartMa();
        }
        //取消编辑
        protected void gvDepartment_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            gvDepartment.EditIndex = -1;
            getDepartMa();
        }
        #endregion

        #region treeView导航点击改变事件
        protected void tvProperty_SelectedNodeChanged(object sender, EventArgs e)
        {      
            if (tvProperty.SelectedValue.Equals("系统管理"))
            {
                tvProperty.SelectedNode.Expand();
            }
            else if (tvProperty.SelectedValue.Equals("系统设置"))
            {
                tvProperty.SelectedNode.Expand();
            }
            else if (tvProperty.SelectedValue.Equals("0"))
            {                  
                right1.Style["display"] = "block";
                right2.Style["display"] = "none";
                right3.Style["display"] = "none";
                right4.Style["display"] = "none";
                right5.Style["display"] = "none";
                propertyShow();
            }
            else if (tvProperty.SelectedValue.Equals("1"))
            {
                right2.Style["display"] = "block";
                right1.Style["display"] = "none";
                right3.Style["display"] = "none";
                right4.Style["display"] = "none";
                right5.Style["display"] = "none";
                getDepartMa();
            }
            else if (tvProperty.SelectedValue.Equals("2"))
            {
                right3.Style["display"] = "block";
                right2.Style["display"] = "none";
                right1.Style["display"] = "none";
                right4.Style["display"] = "none";
                right5.Style["display"] = "none";
                employShow();
            }
            else if (tvProperty.SelectedValue.Equals("3"))
            {
                right4.Style["display"] = "block";
                right2.Style["display"] = "none";
                right3.Style["display"] = "none";
                right1.Style["display"] = "none";
                right5.Style["display"] = "none";
                personSet();
            }
            else if (tvProperty.SelectedValue.Equals("4"))
            {
                right5.Style["display"] = "block";
                right2.Style["display"] = "none";
                right3.Style["display"] = "none";
                right4.Style["display"] = "none";
                right1.Style["display"] = "none";
            }         
        }
        #endregion

        #region 密码修改
        protected void btnChange_Click(object sender, EventArgs e)
        {
            string pwd = txtPassword.Text.Trim();
            string newpwd = txtNewPassword.Text.Trim();
            string celpwd = celPassword.Text.Trim();
            if(pwd.Equals("") || newpwd.Equals("") || celpwd.Equals(""))
            {
                Response.Write("<script>alert('密码不能为空,请补充！')</script>");
                return;
            }
            if (!newpwd.Equals(celpwd))
            {
                Response.Write("<script>alert('密码不一致！')</script>");
                return;
            }
            string id = lblNum.Text;
            var result = db.Employees.Where(em => em.EmpId.ToString() == id && em.Password.Trim() == pwd).FirstOrDefault();
            if(result == null)
            {
                Response.Write("<script>alert('旧密码不正确！')</script>");
            }else
            {
                result.Password = newpwd;
                try
                {
                    db.SaveChanges();
                    Response.Write("<script>alert('修改成功！')</script>");
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }     
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            right4.Style["display"] = "none";
            right5.Style["display"] = "none";
        }
        #endregion

        #region 系统管理新增
        protected void btnUpload_Click(object sender, EventArgs e)
        {
            string image = this.fileImage.PostedFile.FileName.Trim();
            string fixname = image.Substring(image.LastIndexOf(".") + 1).ToLower();
            if (image == "") return;
            if (fixname == "png" || fixname == "jpg" || fixname == "gif")
            {
                string filePath = Server.MapPath(".") + "//image//" + image;
                fileImage.SaveAs(filePath);
                Response.Write("<script>alert('图片已成功上传！')</script>");
            }
            else
            {
                Response.Write("<script>alert('图片格式不正确，上传失败！')</script>");
            }
        }
        protected void btnAdd1_Click(object sender, EventArgs e)
        {
            if(userMa == "是")
            {
                string id = txtPropertyNum.Text.Trim();
                string name = txtPropertyName.Text.Trim();
                string info = txtPropertyInfo.Text.Trim();
                string imagename = txtPropertyImage.PostedFile.FileName.Trim();
                string image = imagename;
                string price = txtPropertyPrice.Text.Trim();
                string locat = txtPropertyLocation.Text.Trim();
                int type = Int32.Parse(ddlPerType.SelectedValue);
                try
                {
                    var result = db.Properties.Where(r => r.ProId.ToString() == id);
                    Property property = new Property();
                    property.ProId = Int32.Parse(id);
                    if (name != "") property.Name = name;
                    if (info != "") property.Specification = info;
                    if (image != "")
                    {
                        string fixname = image.Substring(image.LastIndexOf(".") + 1).ToLower();
                        if(fixname == "png" || fixname == "jpg" || fixname == "gif")
                        {
                            string filePath = Server.MapPath(".") + "//image//" + image;
                            property.Image = image;
                            txtPropertyImage.SaveAs(filePath);
                        }
                        else
                        {
                            Response.Write("<script>alert('图片格式不正确，已为你设置成系统默认图片！')</script>");
                            property.Image = "1.jpg";
                        }
                       
                    }
                    else property.Image = "1.jpg";
                    property.PurchaseDate = DateTime.Now;
                    if (price != "") property.Price = Int32.Parse(price);
                    if (locat != "") property.StoreLocation = locat;
                    property.ProTypeId = type;
                    property.EmpId = Int32.Parse(lblNum.Text);
                    if (result.Count() == 0)
                    {
                        db.Properties.Add(property);
                        db.SaveChanges();
                        propertyShow();
                        right1.Style["display"] = "block";
                    }
                    else
                    {
                        Response.Write("<script>alert('资源中已有该编号')</script>");
                    }

                }
                catch (Exception ex)
                {
                    Response.Write("<script>alert('添加中出现错误，" + ex.Message + "')</script>");
                }
            }
            else
            {
                Response.Write("<script>alert('管理权限不够，无法操作！')</script>");
            }
        }
        protected void btnAdd2_Click(object sender, EventArgs e)
        {     
            if(userTypeMa == "管理部")
            {
                string name = txtDepartName.Text.Trim();
                string info = txtDepartInfo.Text.Trim();
                string id = txtDepartNum.Text.Trim();
                Department department = new Department();
                var result = db.Departments.Where(d => d.DepartId.ToString() == id);
                if (result.Count() == 0)
                {                   
                    department.Count = 0;
                    if (!info.Equals("")) department.Info = info;
                    if (!name.Equals("")) department.Name = name;                 
                    try
                    {
                        department.DepartId = Int32.Parse(id);
                        db.Departments.Add(department);
                        db.SaveChanges();
                        getDepartMa();
                        right2.Style["display"] = "block";
                    }
                    catch (Exception exx)
                    {
                        Response.Write("<script>alert('添加中出现错误，" + exx.Message + "')</script>");
                    }
                }
                else
                {
                    Response.Write("<script>alert('已有该编号')</script>");
                }               
            }
            else
            {
                Response.Write("<script>alert('管理权限不够，无法操作！')</script>");
            }
            
        }
        protected void btnAdd3_Click(object sender, EventArgs e)
        {
            if(userTypeMa == "管理部")
            {
                string id = txtEmplyeeNum.Text.Trim();
                string name = txtEmplyeeName.Text.Trim();
                string pwd = txtEmplyeePwd.Text.Trim();
                string tell = txtEmplyeeTell.Text.Trim();
                string deId = ddlEmplyeeType.SelectedValue;
                string ifmanger = txtEmplyeeManger.SelectedValue;
                bool b = false;
                if (ifmanger.Equals("1")) b = true;
                var re = db.Employees.Where(em => em.EmpId.ToString() == id);
                if (re.Count() == 0)
                {
                    try
                    {
                        Employee employee = new Employee();
                        employee.EmpId = Int32.Parse(id);
                        employee.Password = pwd;
                        employee.Name = name;
                        employee.Tell = tell;
                        employee.DepartId = Int32.Parse(deId);
                        employee.IsManger = b;
                        db.Employees.Add(employee);
                        var de = db.Departments.Where(d => d.DepartId.ToString() == deId).FirstOrDefault();
                        de.Count = de.Count + 1;
                       
                        if (b)
                        {
                            de.EmpId = Int32.Parse(id);
                            var mange = db.Employees.Where(m => m.IsManger == true && m.DepartId.ToString() == deId).FirstOrDefault();
                            if (mange != null)
                            {
                                mange.IsManger = false;
                                var property = db.Properties.Where(p => p.EmpId == mange.EmpId);
                                if(property.Count() != 0)
                                {
                                    foreach (var pp in property)
                                    {
                                        pp.EmpId = Int32.Parse(id);
                                    }
                                }                            
                            }
                        }
                        db.SaveChanges();
                        employShow();
                        getDepartMa();
                        ShowProperty();
                        right3.Style["display"] = "block";
                    }
                    catch (Exception ex)
                    {
                        Response.Write("<script>alert('添加中出现错误，" + ex.Message + "')</script>");
                    }
                }
                else
                {
                    Response.Write("<script>alert('已有该编号')</script>");
                }
            }else
            {
                Response.Write("<script>alert('管理权限不够，无法操作！')</script>");
            }
            
        }
        #endregion

        #region gridView员工相关操作
        //删除和修改定位是全部显示还是部门显示，还是个人显示
        private void employShow()
        {
            string ddlname = ddlType3.SelectedItem.Text;
            string search = txtSearch3.Text.Trim();
            if(ddlname.Equals("-请选择-") && search.Equals("请输入员工编号或名字"))
            {
                getEmployeeData();
            }else if(!ddlname.Equals("-请选择-") && search.Equals("请输入员工编号或名字"))
            {
                ddlEmploy();
            }else
            {
                searchEmploy();
            }
        }
        //获取全部员工
        private void getEmployeeData()
        {
            var result = from em in db.Employees
                         join d in db.Departments
                         on em.DepartId equals d.DepartId
                         where em.DepartId != 520
                         select new
                         {
                             编号 = em.EmpId,
                             密码 = userTypeMa.Equals("管理部")? em.Password : "******",
                             名称 = em.Name,
                             部门 = d.Name,
                             电话 = em.Tell,
                             管理 = em.IsManger==true
                         };
            if (result == null)
            {
                Response.Write("<script>alert('系统中没有员工相关数据！')</script>");
            } 
            try
            {                            
                gvEmployee.DataSource = result.ToList();
                gvEmployee.DataBind();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            
        }
        //下拉框
        private void ddlEmploy()
        {
            int id = Int32.Parse(ddlType3.SelectedValue);
            txtSearch3.Text = "请输入员工编号或名字";
            string name = ddlType3.SelectedItem.Text.Trim();
            if (id == 0)
            {
                getEmployeeData();
            }
            else
            {
                var result = from em in db.Employees
                             join d in db.Departments
                             on em.DepartId equals d.DepartId
                             where em.DepartId == id
                             select new
                             {
                                 编号 = em.EmpId,
                                 密码 = userTypeMa.Equals("管理部") ? em.Password : "******",
                                 名称 = em.Name,
                                 部门 = d.Name,
                                 电话 = em.Tell,
                                 管理 = em.IsManger == true
                             };
                if (result.Count() == 0)
                {
                    Response.Write("<script>alert('" + name + "在系统中没有相关数据！')</script>");
                }               
                try
                {
                    gvEmployee.DataSource = result.ToList();
                    gvEmployee.DataBind();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }          
            }
        }
        protected void ddlType3_SelectedIndexChanged(object sender, EventArgs e)
        {         
            ddlEmploy();
        }
        //搜索
        private void searchEmploy()
        {
            string search = txtSearch3.Text.Trim();       
            ddlType3.SelectedValue = "0";
            var result = from em in db.Employees
                         join d in db.Departments
                         on em.DepartId equals d.DepartId
                         where em.EmpId.ToString() == search || em.Name.Contains(search)
                         select new
                         {
                             编号 = em.EmpId,
                             密码 = userTypeMa.Equals("管理部") ? em.Password : "******",
                             名称 = em.Name,
                             部门 = d.Name,
                             电话 = em.Tell,
                             管理 = em.IsManger == true
                         };
            if (result.Count() == 0)
            {
                Response.Write("<script>alert('" + search + "在系统中没有相关数据！')</script>");
            }
            try
            {
                gvEmployee.DataSource = result.ToList();
                gvEmployee.DataBind();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }            
        }
        protected void btnSearch3_Click(object sender, EventArgs e)
        {
            searchEmploy();
        }
        //换页
        protected void gvEmployee_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            gvEmployee.PageIndex = e.NewPageIndex;
            employShow();
        }
        //取消编辑
        protected void gvEmployee_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            gvEmployee.EditIndex = -1;
            employShow();
        }
        //修饰
        protected void gvEmployee_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                e.Row.Attributes.Add("onmouseover", "bg=this.style.backgroundColor;c=this.style.color;this.style.backgroundColor='#0094ff';this.style.color='#fff';");
                e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=bg;this.style.color=c");
                e.Row.Cells[0].Attributes.Add("style", "border: 1px solid #333");
                e.Row.Cells[1].Attributes.Add("style", "border: 1px solid #333");
                e.Row.Cells[2].Attributes.Add("style", "border: 1px solid #333");
                e.Row.Cells[3].Attributes.Add("style", "border: 1px solid #333");
                e.Row.Cells[4].Attributes.Add("style", "border: 1px solid #333");
                e.Row.Cells[5].Attributes.Add("style", "border: 1px solid #333");
                e.Row.Cells[6].Attributes.Add("style", "border: 1px solid #333");
                e.Row.Cells[7].Attributes.Add("style", "border: 1px solid #333");
                try
                {
                    //获取“删除”链接
                    LinkButton lnkbtnDelete = (LinkButton)e.Row.Cells[7].Controls[0];
                    //添加JavaScript代码实现客户端信息的提示
                    lnkbtnDelete.OnClientClick = "return confirm('您真要删除员工名称为" +
                e.Row.Cells[2].Text.Trim() + "的记录吗?');";
                }
                catch
                {
                    return;
                }
            }
        }
        //删除
        protected void gvEmployee_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            if (userTypeMa == "管理部")
            {
                string id = gvEmployee.Rows[e.RowIndex].Cells[0].Text.Trim().ToString();
                var result = db.Employees.Where(r => r.EmpId.ToString() == id).FirstOrDefault();               
                var emp = db.Employees.Where(em => em.DepartId == result.DepartId);
                var de = db.Departments.Where(d => d.DepartId == result.DepartId).FirstOrDefault();
                string c = de.Count.ToString();
                de.Count = Int32.Parse(c) - 1;
                if (result.IsManger == true)               {
                    de.EmpId = null;
                    var property = db.Properties.Where(p => p.EmpId.ToString() == id);
                    if (property.Count() != 0)
                    {
                        foreach (var pp in property)
                        {
                            pp.EmpId = null;
                        }
                        ShowProperty();
                    }
                }            
                db.Employees.Remove(result);
                db.SaveChanges();
                getDepartMa();
                employShow();               
            }
            else
            {
                Response.Write("<script>alert('管理权限不够，无法操作！')</script>");
            }

        }
        //编辑
        protected void gvEmployee_RowEditing(object sender, GridViewEditEventArgs e)
        {
            gvEmployee.EditIndex = e.NewEditIndex; //切换到编辑状态
            employShow();
        }
        //更新
        protected void gvEmployee_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            if (userTypeMa == "管理部")
            {
                string id = gvEmployee.Rows[e.RowIndex].Cells[0].Text.Trim().ToString();
                string pwd = ((TextBox)(gvEmployee.Rows[e.RowIndex].Cells[1].Controls[0])).Text.Trim().ToString();
                string name = ((TextBox)(gvEmployee.Rows[e.RowIndex].Cells[2].Controls[0])).Text.Trim().ToString();
                string deName = ((TextBox)(gvEmployee.Rows[e.RowIndex].Cells[3].Controls[0])).Text.Trim().ToString();
                string tell = ((TextBox)(gvEmployee.Rows[e.RowIndex].Cells[4].Controls[0])).Text.Trim().ToString();
                string ismanger;
                if (((CheckBox)(gvEmployee.Rows[e.RowIndex].Cells[5].Controls[0])).Checked == true)
                    ismanger = "是";
                else ismanger = "否";
                var result = db.Employees.Where(em => em.EmpId.ToString() == id).FirstOrDefault();
                if (pwd != "") result.Password = pwd;
                if (name != "") result.Name = name;
                if (tell != "") result.Tell = tell;
                if (deName != "")
                {
                    var de1 = db.Departments.Where(d => d.Name == deName).FirstOrDefault();//获取修改的
                    if (de1 != null)
                    {
                        if (de1.DepartId != result.DepartId)
                        {
                            result.DepartId = de1.DepartId;
                            result.IsManger = false;
                        }
                        else
                        {
                            if (ismanger != "")
                            {
                                bool ifm = false;
                                if (ismanger == "是")
                                {
                                    ifm = true;
                                    if (result.IsManger != ifm)
                                    {
                                        var em2 = db.Employees.Where(em => em.DepartId == result.DepartId && em.IsManger == true).FirstOrDefault();
                                        if (em2 != null)
                                        {
                                            em2.IsManger = false;
                                            var property = db.Properties.Where(p => p.EmpId == em2.EmpId);
                                            if (property.Count() != 0)
                                            {
                                                foreach (var pp in property)
                                                {
                                                    pp.EmpId = Int32.Parse(id);
                                                }
                                                ShowProperty();
                                            }
                                        }
                                        result.IsManger = true;
                                        var de2 = db.Departments.Where(d => d.DepartId == result.DepartId).FirstOrDefault();//获取修改的
                                        if (de2 != null)
                                        {
                                            de2.EmpId = Int32.Parse(id);
                                        }
                                    }
                                }
                                else
                                {
                                    if (result.IsManger != ifm)
                                    {
                                        result.IsManger = false;
                                        var de3 = db.Departments.Where(d => d.EmpId.ToString() == id).FirstOrDefault();//获取修改的
                                        if (de3 != null)
                                        {
                                            de3.EmpId = null;
                                            var property1 = db.Properties.Where(p => p.EmpId.ToString() == id);
                                            if (property1.Count() != 0)
                                            {
                                                foreach (var pp in property1)
                                                {
                                                    pp.EmpId = null;
                                                }
                                                ShowProperty();
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    else
                    {
                        Response.Write("<script>alert('系统中没有部门名称为" + deName + "')</script>");
                        return;
                    }
                }
                try
                {
                    db.SaveChanges();
                    gvEmployee.EditIndex = -1;
                    employShow();
                    getDepartMa();
                }
                catch (Exception ex)
                {
                    Response.Write("<script>alert('修改中出现错误，" + ex.Message + "')</script>");
                }
            }
            else
            {
                gvEmployee.EditIndex = -1;
                employShow();
                Response.Write("<script>alert('管理权限不够，无法操作！')</script>");
            }
        }
        #endregion
    }
}